import {Component, Inject, ViewChild} from '@angular/core';
import { Content, IonicPage, ModalController, NavController} from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';
import { Subscription } from 'rxjs/Subscription';
// picker
import { convertEnumToColumn } from 'ion-multi-picker';
// 枚举
import { EducationGradeEnum } from '../../../../config/enum';
// service
import { AlertService } from '../../../../providers/utils/alert.service';
// 常量
import * as PageConstant from '../../../../constant/pageConstant';

// utils
import { spliceAddress, sliceBase64 } from '../../../../utils/basic';

/**
 * 个人信息
 */
@IonicPage()
@Component({
  selector: 'page-mine-home',
  templateUrl: 'mine-home.html'
})
export class MineHomePage{

  @ViewChild(Content) content: Content;
  // 是否验证
  private idState: any;
  // 用户信息
  private idInfo: any;
  // 人脸和身份证对比值返回数据
  private faceInfo: any;
  // 教育背景
  private educationGrade: Array<any>;
  private initGrade: any;

  // 人脸识别
  private faceImageUrl: any;
  // 身份证识别
  private frontCardUrl: any;
  private backCardUrl: any;

  // 地址信息
  private address: string;
  private detailAddress: string;

  // 监听 用户信息
  private userSubscription: Subscription;
  private KeyboardShow: Subscription;
  private KeyboardHide: Subscription;

  constructor(
    private navCtrl: NavController,
    public modalCtrl: ModalController,
    private keyboard: Keyboard,
    private alertCtrl : AlertService,
    @Inject('user') private userService
  )
  {
    this.userSubscription= this.userService.getUser()
      .filter(user=> user.userId)
      .subscribe(user => {
        this.idState= user.idState;
        this.idInfo= user.idInfo;

        // 解析地址
        const { address, detailAddress }= spliceAddress(user.idInfo.liveAddress);
        this.address= address;
        this.detailAddress= detailAddress;

        this.faceInfo= user.faceInfo;
        let education = user.idInfo.education?
          EducationGradeEnum[Number(user.idInfo.education)-1]
          :
          '本科';
        this.initPicker(education);
      })
  }
  ionViewWillEnter()
  {
    this.initSubscription();
  }
  /*** 页面离开
   * */
  ionViewWillLeave()
  {
    this.removeSubscription();
  }
  /*** 初始化监听
   * */
  private initSubscription(): void
  {
    this.KeyboardShow= this.keyboard.onKeyboardShow().subscribe(data=>{
      if(!data) return;
      this.scrollToBottom();
    });

    this.KeyboardHide= this.keyboard.onKeyboardHide().subscribe(data=>{
      if(!data) return;
    });

  }
  // 滚动到底部
  scrollToBottom()
  {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom();
      }
    }, 400)
  }
  /*** 移除监听
   * */
  private removeSubscription(): void
  {
    if(typeof this.KeyboardShow !== 'undefined')
      this.KeyboardShow.unsubscribe();

    if(typeof this.KeyboardHide !== 'undefined')
      this.KeyboardHide.unsubscribe();

    if(typeof this.userSubscription !== 'undefined')
      this.userSubscription.unsubscribe();
  }
  /*** 初始化picker
   * @param education 初始化值
  * */
  initPicker(education: string)
  {
    this.initGrade = EducationGradeEnum[education];
    this.educationGrade = convertEnumToColumn(EducationGradeEnum);
  }

  /*** 人脸识别前面数据
   * */
  getFaceImage(event)
  {
    this.faceImageUrl= event.value.url;
    let faceImageUrl= sliceBase64(this.faceImageUrl);
    let frontCardUrl= sliceBase64(this.frontCardUrl);
    this.userService.getFaceContrastByUploadImage(faceImageUrl, frontCardUrl);
  }
  resetFaceImage()
  {
    this.faceImageUrl= null;
  }

  /*** 身份证前面数据
   * */
  getFrontCard(event)
  {
    this.frontCardUrl = event.value.url;
    let faceImageUrl= sliceBase64(this.faceImageUrl);
    let frontCardUrl= sliceBase64(this.frontCardUrl);
    this.userService.getIdCardByUploadImage(frontCardUrl);
    this.userService.getFaceContrastByUploadImage(faceImageUrl, frontCardUrl);
  }
  resetFrontCard()
  {
    this.frontCardUrl= null;
  }
  /*** 身份证后面数据
   * */
  getBackCard(event)
  {
    this.backCardUrl= event.value.url;
  }

  resetBackCard()
  {
    this.backCardUrl= null;
  }

  /*** 选择地址
  * */
  protected choiceAddress(): void
  {
    let modal = this.modalCtrl.create(PageConstant.LoadMapPage, {},{
      showBackdrop: false,
      enableBackdropDismiss: false,
    });
    modal.onDidDismiss(address => {
      if(!address) return;
      this.address= address;
    });
    modal.present();
  }

  /*** 执行保存
   * 情况1： 当idState为真, 代表已认证
   * 情况2： 当idState为假, 代表新用户未认证(拿this.idInfo中的地址信息)
  * */
  public executeSave(): void
  {
    const idState= this.idState;
    let livingImg, frontImg, backImg;

    // 判断idState
    if(idState) {
      livingImg= this.idInfo.livingImg;
      frontImg= this.idInfo.frontImg;
      backImg= this.idInfo.backImg;

    }else{
      // 新注册拿页面数据
      livingImg= sliceBase64(this.faceImageUrl);
      frontImg= sliceBase64(this.frontCardUrl);
      backImg= sliceBase64(this.backCardUrl);
    }
    let { pass, compareFaceVal }= this.faceInfo;
    const liveAddr= `${this.address}#${this.detailAddress}`;
    // 转换学历
    let education= this.educationGrade[0].options[this.initGrade].text;
    education= Number(EducationGradeEnum[education])+1;

    const { realname, idNo }= this.idInfo;
    if(!(this.address&&this.detailAddress&&livingImg&&frontImg&&backImg&&education&& realname&&idNo)){
      this.alertCtrl.createAgreeAlert('信息不完善');
      return;
    }

    // 再次注册直接提交信息
    if(idState) {
        const options= { liveAddr, education };
        this.userService.onlyUpdateUserInfo(options, this.navCtrl);
       return;
    }

    pass= Number(pass);
    // 若对比不成功直接提示用户
    if(!pass){
      this.alertCtrl.createAgreeAlert('请确定本人信息与身份证一致');
      return;
    }

    // 第一次认证逻辑
    this.alertCtrl.createMessageAlert(
      `请确认提交信息`,
      `姓名:${realname}<br/>身份证号:${idNo}`
      )
      .then(status=>{
      if(!status) return;
        let options= { liveAddr, livingImg, frontImg,
          backImg, education, pass, compareFaceVal, realname,
          idNo, idState: 1 };
      this.userService.uploadImageAndUpdateUserInfo(options, this.navCtrl);
    });
  }

}

